package com.cxlin.cwanandroid.ui.me

import android.widget.Toast
import com.cxlin.base.BaseFragment
import com.cxlin.base.ext.binding
import com.cxlin.base.ext.startActivity
import com.cxlin.base.ext.toast
import com.cxlin.base.mvi.ext.collectFLow
import com.cxlin.cwanandroid.R
import com.cxlin.cwanandroid.databinding.FragmentMeBinding
import com.cxlin.cwanandroid.ui.login.LoginActivity
import com.cxlin.cwanandroid.ui.login.viewmodel.LoginViewModel
import com.cxlin.cwanandroid.ui.me.viewmodel.MeViewModel
import de.psdev.licensesdialog.LicensesDialog
import de.psdev.licensesdialog.licenses.ApacheSoftwareLicense20
import de.psdev.licensesdialog.model.Notice
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/29 11:13
 */
class MeFragment : BaseFragment() {

    private val binding by binding<FragmentMeBinding>()
    private val viewModel by viewModel<MeViewModel>()

    private val GITHUB_PAGE = "https://github.com/lulululbj/wanandroid"
    override fun getLayoutId() = R.layout.fragment_me

    override fun initView() {
    }

    override fun initData() {
        binding.apply {
            license.setOnClickListener {
                showOwnLicense()
            }
            thirdLib.setOnClickListener {
                showLicenseDialog()
            }
        }

    }

    override fun observeStateAndEvent() {
        viewModel.uiStateFlow.collectFLow(this) {
            when (this) {
                is MeViewModel.MeUiState.User -> {
                    binding.loginTv.text = if (this.result != null) this.result.nickname else "登录/注册"
                    binding.loginTv.setOnClickListener {
                        if (this.result == null) {
                            requireActivity().startActivity<LoginActivity>()
                        }
                    }
                }

                else -> {}
            }
        }

        viewModel.effectFlow.collectFLow(this) {
            when (this) {
                is LoginViewModel.LoginEvent.ToastEvent -> {
                    requireActivity().toast(
                        this.message,
                        if (this.short) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
                    )
                }
            }
        }
    }

    private fun showOwnLicense() {
        val notice =
            Notice(getString(R.string.app_name), GITHUB_PAGE, "", ApacheSoftwareLicense20())
        LicensesDialog.Builder(activity)
            .setNotices(notice)
            .build()
            .show()
    }

    private fun showLicenseDialog() {
        LicensesDialog.Builder(activity)
            .setNotices(R.raw.licenses)
            .build()
            .show()
    }

    override fun onStart() {
        super.onStart()
        viewModel.registerEvent()
    }

    override fun onStop() {
        super.onStop()
        viewModel.unRegisterEvent()
    }
}